package com.exmaple.cdc.lock;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Logger;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/2/28 下午11:59
 */
public class MySqlLock {

    Logger logger = Logger.getLogger(getClass().getName());

    private DataSource dataSource;

    private Connection connection;

    private boolean connAutoCommit = false;

    private PreparedStatement preparedStatement;

    private String SQL = "select * from sys_lock where id = 1 for update";

    public MySqlLock(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /****
     * 获取锁并执行业务操作
     * @throws Exception
     */
    public void lock() throws Exception {
        this.connection = this.dataSource.getConnection();
        this.connAutoCommit = connection.getAutoCommit();
        this.connection.setAutoCommit(false);
        this.preparedStatement = connection.prepareStatement(SQL);
        this.preparedStatement.execute();
    }

    /****
     * 释放锁并关闭连接
     * @throws Exception
     */
    public void unlock() {
        if (connection != null) {
            try {
                connection.commit();
            } catch (SQLException e) {
                logger.warning("connection commit error: " + e.getMessage());
            }
        }
        try {
            if (connection != null) {
                connection.setAutoCommit(connAutoCommit);
            }
        } catch (SQLException e) {
            logger.warning("connection set autocommit error: " + e.getMessage());
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.warning("connection close error: " + e.getMessage());
            }
        }
        if (null != preparedStatement) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                logger.warning("preparedStatement close error: " + e.getMessage());
            }
        }
    }
}

